<?php

/**
 * @property StudentUser $StudentUser Description
 * @property BankUser $BankUser Description
 * @property Transaction $Transaction Description
 * @property Config $Config Description
 * @property TransactionBankDetail $TransactionBankDetail Description
 */
class BankController extends AppController
{
    # Controller Name to be used

    var $name = 'Bank';


    # Models to be used
    var $uses = array(
        'BankUser', 'StudentUser', 'BankBranch', 'Transaction', 'Config', 'TransactionBankDetail', 'StudentNotification',
        'BankReportTracking', 'FeeType', 'BankReportTracking', 'BankReportLog', 'BankFailedLogin','BankCreditAuthorization',
        'BankReversalAuthorization','BankBatch','Bank','StudentWallet'
    );

    # set the layout to use
    var $layout = 'bank_layout';

    public function beforeFilter() {
        parent::beforeFilter();

    }


    public function login()
    {
        $this->autoRender = false;

        $data = $this->request->data;
        $data  = $this->BankUser->sanitize($data);
        $username = $data['username'];
        $password = $data['password'];
        $status = false;
        $return_arr = array();
        $msg = '';
        $result_login = $this->BankUser->login($username, $password);
        if ($result_login['status']) {
            $status = true;
            $return_arr = $result_login;
            $msg = 'Login Success!';
        } else {
            $status = false;
            $return_arr = $result_login;
            $msg = $result_login['msg'];
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }


    public function search()
    {
        $this->autoRender = false;

        $data = $this->request->data;

        $index_number = $data['index_number'];
        if(isset($data['bank_id'])){
            $bank_id = $data['bank_id'];
        }
        else{
            $branch_id = $data['branch_id'];
            $bank_info = $this->getUserBankDetails($branch_id);
            $bank_id = $bank_info['Bank']['id'];
        }



        $student = $this->StudentUser->find('first', array(
                'fields'=>array('StudentUser.id','StudentUser.index_number','StudentUser.reg_no','StudentUser.fname','StudentUser.mname','StudentUser.lname','StudentUser.date_of_birth','StudentUser.gender','StudentUser.homephone','StudentUser.cellphone','StudentUser.email','StudentUser.program_id'),
                'contain' => array(
                    'Program'=>array('fields'=>array('Program.id','Program.name')),
                    'StudentWallet'=>array(
                        'fields'=>array('StudentWallet.id','StudentWallet.bank_id','StudentWallet.account_balance'),
                        "Bank"=>array('fields'=>array('Bank.id','Bank.bank','Bank.bank_full'))
                    ),
                    'Transaction' => array(
                        'fields'=>array('Transaction.id','Transaction.bank_user_id','Transaction.trans_ref_no','Transaction.authorize','Transaction.reverted ','Transaction.created'),
                        'conditions' => array(
                            'bank_id'=>$bank_id,
                            'trans_type' => 'credit_account',
                            'reverted' => 0
                        ),
                        'order' => array('id' => 'desc'),
                        'limit' => 5,
                        "TransactionBankDetail"=>array('fields'=>array('TransactionBankDetail.id','TransactionBankDetail.payment_method','TransactionBankDetail.credit_amt ')),
                        "TransactionItem"=>array('fields'=>array('TransactionItem.id','TransactionItem.credit_amt')),
                        "BankUser"=>array('fields'=>array('BankUser.id','BankUser.fname','BankUser.mname','BankUser.lname'))
                    )
                ),
                'conditions' => array(
                    'OR' => array(
                        'StudentUser.index_number' => $index_number)
                ))
        );

        $result = array(
            'response_code'=>1,
            'message'=>'No Student Found With Index Number Supplied',
            'data'=>array()
        );
        if ($student) {
            $result = array(
                'response_code'=>0,
                'message'=>'Student Found With Index Number Supplied',
                'data'=>$student
            );
        }

        return $this->_response($result);
    }



    /**
     * Credit a Student's Account with a Cash or Cheque Payment
     */
    public function credit_account()
    {
        $this->autoRender = false;

        $data = $this->request->data;

        $index_number = isset($data['index_number'])? $data['index_number'] : null;
        $student_id = isset($data['student_id'])? $data['student_id'] : null;
        if($index_number != null){
            $res = $this->StudentUser->checkStudentByIndexNumber($index_number);
            if($res){
                $student_id = $res['StudentUser']['id'];
            }
            else{
                $result = array(
                    'response_code'=>1,
                    'message'=>'Student Account Not Found',
                    'data'=>array()
                );
                return $this->_response($result);
            }
        }
        else{
            if($student_id != null){
                $res = $this->StudentUser->checkStudentById($student_id);
                if($res){}
                else{
                    $result = array(
                        'response_code'=>1,
                        'message'=>'Student Account Not Found',
                        'data'=>array()
                    );
                    return $this->_response($result);
                }
            }
        }

        $amount_tendered = doubleval($data['amount_tendered']);
        $branch_id = $data['branch_id'];
        $bank_user_id = $data['bank_user_id'];
        $payee_name = $data['payee_name'];
        $payee_phone= $data['payee_phone'];
        $payee_address= $data['payee_address'];
        $payment_method= $data['payment_method'];
        $payin_cheque_number= isset($data['payin_cheque_number'])?$data['payin_cheque_number']:'';
        $payin_cheque_bank = isset($data['payin_cheque_bank'])?$data['payin_cheque_bank']:'';

        $student_info_data = $this->StudentUser->getUserById($student_id);

        $bank_info = $this->getUserBankDetails($branch_id);
        $bank_id = $bank_info['Bank']['id'];

        $student_info = $student_info_data['StudentUser'];
        $enforce_credit_limit = $bank_info['Bank']['enforce_credit_limit'];
        $credit_limit = ($enforce_credit_limit == 'Y') ? doubleval($bank_info['Bank']['teller_credit_limit']):0;
        $trans_ref_no = "CRA" . $this->Transaction->getNextAutoIncrement() . "001";
        $trans = array(
            'Transaction' => array(
                'trans_type' => 'credit_account',
                'bank_id' => $bank_id,
                'student_user_id' => $student_id,
                'academic_session_id' => $this->Config->get('academic_session_id'),
                'ip_address' => $_SERVER['REMOTE_ADDR'],
                'trans_ref_no' => $trans_ref_no,
                'bank_user_id' => $bank_user_id,
                'created_by' => $bank_user_id,
                'modified_by' => $bank_user_id
            ),
            'TransactionBankDetail' => array(
                array(
                    'bank_branch_id' => $branch_id,
                    'teller_id' => $bank_user_id,
                    'payee_name' => $payee_name,
                    'payee_phone' => $payee_phone,
                    'payee_address' => $payee_address,
                    'credit_account' => $bank_info['Bank']['credit_acc_no'],
                    'credit_amt' => $amount_tendered,
                    'debit_account' => null,
                    'payment_method' => $payment_method,
                    'payin_cheque_number' => $payin_cheque_number,
                    'payin_bank' => $payin_cheque_bank,
                    'created_by' => $bank_user_id
                )
            ),
            'TransactionItem' => array(
                array(
                    'fee_id' => null,
                    'trans_currency' => 'GHS',
                    'credit_amt' => $amount_tendered,
                    'desc' => 'Credit Account'
                )
            )
        );
        if($enforce_credit_limit == 'Y'){
            if($amount_tendered >= $credit_limit){//Send for Authorization,
                $trans['BankCreditAuthorization'] = array(
                    'bank_id'=>$bank_id,
                    'bank_user_id'=>$bank_user_id,
                    'bank_branch_id'=>$branch_id,
                    'authorize_amount'=>$amount_tendered,
                );
                $trans['Transaction']['authorize'] = 'Pending';
            }
        }

        $saved = $this->Transaction->saveAll($trans);
        $date_of_payment = date('Y-m-d');
        $status = false;
        if ($saved) {
            if($enforce_credit_limit == 'Y'){
                if($amount_tendered >= $credit_limit){//Send for Authorization,
                    $msg = "Dear " . $student_info['fname'] . " an amt of GHS " . doubleval($amount_tendered) . " will be credited to your UPSA wallet in an hours time from now. If your wallet is not credited by then, please contact Access Bank. Visit http://interpayafrica.com/student to check your balance and complete payment. ";
                    $notify_msg = "Your UPSA account will be credited with <b> GHC " . doubleval($amount_tendered) . "</b> in an hours time from now. If your wallet is not credited by then, please contact Access Bank";
                }
                else{
                    $student_new_bal = $this->StudentUser->creditAccount($student_id, doubleval($amount_tendered),$bank_id);
                    $bal = $student_new_bal;
                    $msg = "Dear " . $student_info['fname'] . " an amt of GHS " . doubleval($amount_tendered) . " has been credited to your UPSA wallet. Your bal. is GHS " . $bal . ". Visit http://interpayafrica.com/student to complete payment. ";
                    $notify_msg = "Your UPSA account was credited with <b> GHC " . doubleval($amount_tendered) . "</b> on <b>" . date('D M d, Y') . "</b> at <b>" . date('g:ia') . "</b>";
                }
            }
            else{
                // update student account balance
                $student_new_bal = $this->StudentUser->creditAccount($student_id, doubleval($amount_tendered),$bank_id);
                $bal = $student_new_bal;
                $msg = "Dear " . $student_info['fname'] . " an amt of GHS " . doubleval($amount_tendered) . " has been credited to your UPSA wallet. Your bal. is GHS " . $bal . ". Visit http://interpayafrica.com/student to complete payment. ";
                $notify_msg = "Your UPSA account was credited with <b> GHC " . doubleval($amount_tendered) . "</b> on <b>" . date('D M d, Y') . "</b> at <b>" . date('g:ia') . "</b>";
            }

            $status = true;

            //send system notifications
            $this->StudentNotification->save(array(
                'StudentNotification' => array(
                    'student_user_id' => $student_id,
                    'notify_title' => 'Account Update Notification',
                    'notify_msg' => $notify_msg
                )
            ));

            $fon_number = $student_info['cellphone'];
            $this->Message->sendSMS($msg, $fon_number);
        }
        else {
            $status = false;
        }

        $result = array(
            'response_code'=>1,
            'message'=>'Could Not Credit Student Account',
            'data'=>array()
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>'Student Account Credited',
                'data'=>array(
                    'trans_ref_no'=>$trans_ref_no,
                    'date_of_payment'=>$date_of_payment,
                    'account_credit'=>$student_info['fname'].' '.$student_info['lname'].' ('.$student_info['index_number'].')',
                    'credit_amount'=>$amount_tendered,
                    'paid_in_by'=>$payee_name
                )
            );
        }

        return $this->_response($result);
    }


    private function getUserBankDetails($branch_id)
    {
        $data = $this->BankBranch->find('first', array(
            'conditions' => array('BankBranch.id' => $branch_id),
            'contain'=>array('Bank'),
            'recursive' => 1
        ));
        return $data;
    }


    public function authorize_transaction(){

        $this->autoRender = false;

        $data = $this->request->data;
        $bank_user_id = $data['bank_user_id'];
        $bank_id = $data['bank_id'];
        if(isset($data['transaction_auth_id'])){
            $auth_id = $data['transaction_auth_id'];
        }
        else{
            $trans_ref_no = $data['trans_ref_no'];
            $trans = $this->Transaction->find('first',array(
                'fields'=>array('Transaction.id'),
                'conditions'=>array('Transaction.trans_ref_no'=>$trans_ref_no,'Transaction.authorize'=>'Pending'),
                'contain' => array(
                    'BankCreditAuthorization'=>array('fields'=>array('BankCreditAuthorization.id'))
                )
            ));

            if($trans){
                $auth_id = $trans['BankCreditAuthorization']['id'];
            }
            else{
                $result = array(
                    'response_code'=>1,
                    'message'=>"Transaction Already Authorized Or Not Found",
                    'data'=>array()
                );
                return $this->_response($result);
            }
        }

        $status = false;
        $return_arr = array();
        $msg = '';

        $auth_data = $this->BankCreditAuthorization->find('first',array(
            'conditions'=>array('BankCreditAuthorization.id'=>$auth_id,'BankCreditAuthorization.status'=>'Not Authorized','BankCreditAuthorization.reverted'=>'Not Reverted'),
            'contain' => array(
                'Transaction'=>array(
                    'StudentUser'
                )
            )
        ));

        if(!$auth_data){
            $result = array(
                'response_code'=>1,
                'message'=>"Transaction Already Authorized Or Not Found",
                'data'=>array()
            );
            return $this->_response($result);
        }

        $authorized_status = $auth_data['BankCreditAuthorization']['status'];

        if($authorized_status == 'Not Authorized'){
            $credit_amount = doubleval($auth_data['BankCreditAuthorization']['authorize_amount']);
            $student_id = $auth_data['Transaction']['StudentUser']['id'];
            $student_fname = $auth_data['Transaction']['StudentUser']['fname'];
            $student_info = $auth_data['Transaction']['StudentUser'];
            //Credit Student Wallet
            $student_new_bal = $this->StudentUser->creditAccount($student_id,$credit_amount,$bank_id);
            if($student_new_bal){
                $bal = $student_new_bal;
                $msg = "Dear " . $student_fname . " an amt of GHS " . $credit_amount . " has been credited to your UPSA wallet. Your bal. is GHS " . $bal . ". Visit http://interpayafrica.com/student to complete payment. ";
                $notify_msg = "Your UPSA account was credited with <b> GHC " . $credit_amount . "</b> on <b>" . date('D M d, Y') . "</b> at <b>" . date('g:ia') . "</b>";

                //send system notifications
                $this->StudentNotification->save(array(
                    'StudentNotification' => array(
                        'student_user_id' => $student_id,
                        'notify_title' => 'Account Update Notification',
                        'notify_msg' => $notify_msg
                    )
                ));

                $fon_number = $student_info['cellphone'];
                $this->Message->sendSMS($msg, $fon_number);

                //Change status to authorize
                $s= array(
                    'Transaction' => array(
                        'id' => $auth_data['Transaction']['id'],
                        'authorize' => 'Authorized',
                        'modified_by' => $bank_user_id
                    ),
                    'BankCreditAuthorization' => array(
                        'id' => $auth_id,
                        'status' => 'Authorized',
                        'modified_by' => $bank_user_id
                    )
                );
                $this->Transaction->saveAll($s);

                $status = true;
                $msg = 'Transaction Authorized!';
            }
            else{
                $status = false;
                $msg = 'Failed Transaction Authorization';
            }
        }
        elseif($authorized_status == 'Authorized'){
            $status = false;
            $msg = 'Transaction Already Authorized';
        }
        else{
            $status = false;
            $msg = 'Invalid Transaction Authorized';
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }


    public function transactions()
    {
        $this->autoRender = false;

        $data = $this->request->data;
        $start_dt = $data['start_dt'];
        $end_dt = $data['end_dt'];
        $type = $type_check ='';
        $type_arr =array();
        $type_check_arr =array();
        $type_arr_data = explode(',',$data['type']);
        foreach($type_arr_data as $typ){
            $type_arr[] = "'".$typ."'";
            $type_check_arr[] = $typ;
        }
        $type = implode(',',$type_arr);
        $type_check = implode(',',$type_check_arr);
        $bank_id = $data['bank_id'];
        $branch = isset($data['filter_branch'])?$data['filter_branch']:null;
        $teller = isset($data['filter_teller'])?$data['filter_teller']:null;
        $reference =  isset($data['filter_trans_ref_no'])?$data['filter_trans_ref_no']:null;
        $status = false;
        $return_arr = array();

        $conditions_str = " WHERE Transaction.trans_type IN ($type) AND Transaction.bank_id = $bank_id";
        if($reference !=null){
            $conditions_str .= " AND Transaction.trans_ref_no='" . $reference . "'";
        }
        else{
            if ($branch != null) {
                $conditions_str .= " AND BankUser.bank_branch_id='" . $branch . "'";
            }
            if ($teller != null) {
                $conditions_str .= " AND Transaction.bank_user_id='" . $teller . "'";
            }
            $cond_date = 'Transaction.created';
            if($type_check == 'credit_reversal'){
                $cond_date = 'Transaction.revert_dt';
            }
            if (!empty($start_dt) || !empty($end_dt)) {
                if (!empty($start_dt) && empty($end_dt)) {
                    $conditions_str .= " AND DATE($cond_date) >='" . $start_dt . "' AND DATE($cond_date) <='" . $start_dt . "'";
                } elseif (empty($start_dt) && !empty($end_dt)) {
                    $conditions_str .= " AND DATE($cond_date) >='" . date('Y-m-d') . "' AND DATE($cond_date) <='" . $end_dt . "'";
                } elseif (!empty($start_dt) && !empty($end_dt)) {
                    $conditions_str .= " AND DATE($cond_date) >='" . $start_dt . "' AND DATE($cond_date) <='" . $end_dt . "'";
                }
            }
        }

        $joins = " LEFT JOIN transaction_bank_details AS TransactionBankDetail ON Transaction.id=TransactionBankDetail.transaction_id";
        $joins .= " LEFT JOIN transaction_items AS TransactionItem ON Transaction.id=TransactionItem.transaction_id";
        $joins .= " LEFT JOIN bank_users AS BankUser ON Transaction.bank_user_id=BankUser.id";
        $joins .= " LEFT JOIN bank_branches AS BankBranch ON BankUser.bank_branch_id=BankBranch.id";
        $joins .= " LEFT JOIN student_users AS StudentUser ON Transaction.student_user_id=StudentUser.id";

        $fields_str = " Transaction.id,Transaction.authorize,Transaction.created,Transaction.trans_type,Transaction.bank_user_id,Transaction.trans_ref_no,Transaction.reverted,Transaction.revert_reason,Transaction.revert_dt,Transaction.reverted_by,";
        $fields_str .= " TransactionItem.id,TransactionItem.desc,TransactionItem.credit_amt,TransactionItem.debit_amt,TransactionItem.transaction_id,";
        $fields_str .= " TransactionBankDetail.id,TransactionBankDetail.payee_name,TransactionBankDetail.payee_phone,TransactionBankDetail.payee_address,TransactionBankDetail.payment_method,";
        $fields_str .= " BankUser.id,BankUser.username,BankUser.fname,BankUser.mname,BankUser.lname,";
        $fields_str .= " BankBranch.id,BankBranch.branch_name,BankBranch.branch_name_full,";
        $fields_str .= " StudentUser.id,StudentUser.index_number,StudentUser.fname,StudentUser.mname,StudentUser.lname";

        $query = "SELECT $fields_str FROM transactions AS Transaction $joins $conditions_str ORDER BY Transaction.id DESC;";

        $data_table = $this->Transaction->query($query);
        if($data_table){
            $status = true;
            foreach($data_table as $key => $value){
                $student_id = $value['StudentUser']['id'];
                $reverted_by = $value['Transaction']['reverted_by'];
                $query = "SELECT StudentWallet.id,StudentWallet.bank_id,StudentWallet.account_balance,Bank.bank FROM student_wallets AS StudentWallet LEFT JOIN banks AS Bank ON StudentWallet.bank_id=Bank.id WHERE StudentWallet.student_user_id=".$student_id;
                $stu_wal = $this->StudentWallet->query($query);
                $data_table[$key]['StudentWallet'] = $stu_wal;

                if($type_check == 'credit_reversal'){
                    $reverted_by = $value['Transaction']['reverted_by'];
                    $query = "SELECT BankUser.id,BankUser.username,BankUser.fname,BankUser.mname,BankUser.lname FROM bank_users AS BankUser WHERE BankUser.id=".$reverted_by;
                    $bnk_usr = $this->BankUser->query($query);
                    $data_table[$key]['ReversedBy'] = $bnk_usr[0]['BankUser'];
                }
            }

        }

        $result = array(
            'response_code'=>1,
            'message'=>"No Transactions Found.",
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>"Transactions Found.",
                'data'=>$data_table
            );
        }

        return $this->_response($result);
    }


    public function revert_transaction()
    {
        $this->autoRender = false;

        $data = $this->request->data;
        $bank_user_id = $data['bank_user_id'];
        $bank_id = $data['bank_id'];
        $transaction_id = $data['transaction_id'];
        $debit_amt = $data['debit_amt'];
        $reason = $data['reason'];
        $status = false;
        $return_arr = array();
        $msg = '';

        $trans = $this->Transaction->find('first', array(
            'conditions' => array(
                'Transaction.id' => $transaction_id,
                'Transaction.bank_id' => $bank_id,
                'Transaction.trans_type' => 'credit_account'
            ),
            'contain'=>array(
                'StudentUser','BankCreditAuthorization'
            )
        ));
        $stu = $trans['StudentUser'];

        if (!$trans) {
            $status = false;
            $return_arr = array();
            $msg = 'No Transaction Found To Revert';
        }
        else {
            //if it required credit authorization
            $debit = true;
            $credit_authorized = false;
            $is_authorized = false;
            if(!empty($trans['BankCreditAuthorization']['id'])){
                $credit_authorized = true;
            }
            if($credit_authorized){
                if($trans['BankCreditAuthorization']['status'] == 'Authorized'){
                    $is_authorized = true;
                }
                else{
                    $debit = false;
                }
            }

            //Reverse the transaction
            $transaction  = array(
                'Transaction'=>array(
                    'id' => $transaction_id,
                    'trans_type'=>'credit_reversal',
                    'revert_dt'=>date('Y-m-d H:i:s'),
                    'reverted'=>1,
                    'reverted_by' => $bank_user_id,
                    'reversal_id' => $transaction_id,
                    'revert_reason'=>$reason,
                    'modified_by' => $bank_user_id
                )
            );
            if($credit_authorized){
                $transaction['BankCreditAuthorization']=array(
                    'id' => $trans['BankCreditAuthorization']['id'],
                    'reverted'=>'Reverted',
                    'modified_by' => $bank_user_id
                );
            }

            $result = $this->Transaction->saveAll($transaction);

            if($result){
                if($debit){
                    $student_new_bal = $this->StudentUser->debitAccount($trans['StudentUser']['id'], doubleval($debit_amt),$bank_id);
                    $bal = $student_new_bal;
                    $msg = "Dear " . $stu['fname'] . " an amt of GHS " . $debit_amt . " has been debited from your UPSA wallet.. Your bal. is GHS " . $bal . "";
                    $notify_msg = "Your UPSA account was debited with <b> GHC " . $debit_amt . "</b> on <b>" . date('D M d, Y') . "</b> at <b>" . date('g:ia') . "</b>";

                    //send system notifications
                    $this->StudentNotification->save(array(
                        'StudentNotification' => array(
                            'student_user_id' => $stu['id'],
                            'notify_title' => 'Account Update Notification',
                            'notify_msg' => $notify_msg
                        )
                    ));

                    $fon_number = $stu['cellphone'];
                    $this->Message->sendSMS($msg, $fon_number);
                }
            }

            if($result){
                $status = true;
                $return_arr = array('is_authorized'=>$is_authorized,'has_authorize'=>$credit_authorized);
                $msg = 'Transaction Reverted!';
            }
            else{
                $status = false;
                $return_arr = array();
                $msg = 'Transaction Reversion Failed!';
            }
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }

    /***************************  BANK ADMIN SECTION *********************/


    public function modify_user()
    {
        $this->autoLayout = false;

        $data = $this->request->data;
        $type = $data['type'];
        $user_id = $data['user_id'];
        $username = $data['username'];
        $fname = $data['fname'];
        $lname = $data['lname'];
        $mname = $data['mname'];
        $user_level = $data['user_level'];
        $active = $data['active'];
        $branch_id = $data['branch_id'];
        $bank_info = $this->getUserBankDetails($branch_id);
        $bank_id = $bank_info['Bank']['id'];
        $bank_user_id = $data['bank_user_id'];
        $status = true;
        $return_arr = array();
        $msg = '';

        $user_data = $this->BankUser->find('first', array(
            'conditions' => array('BankUser.id' => $user_id),
            'recursive' => -1
        ));

        $record_id = $user_id;
        if ($type == 'add') {
            //check if username does not exist for in this company
            $res = $this->_validateUsername($username);
            if ($res) {
                $status = false;
                $return_arr = array();
                $msg = 'Username Already Exist';
            }
            else{
                $status = true;
            }
        }
        else{
            if($user_data){
                $old_username = $user_data['BankUser']['username'];
                $record_id = $user_data['BankUser']['id'];
                if($username != $old_username){
                    $res = $this->_validateUsername($username);
                    if ($res) {
                        $status = false;
                        $return_arr = array();
                        $msg = 'Username Already Exist';
                    }
                    else{
                        $status = true;
                    }
                }
                else{
                    $status = true;
                }
            }
            else{
                $status = false;
                $return_arr = array();
                $msg = 'Username Does Not Exist';
            }

        }

        if (!$status) {
            $result = array(
                'response_code'=>1,
                'message'=>$msg,
                'data'=>$return_arr
            );

            return $this->_response($result);
        }

        $data = array('BankUser' => array(
            'id'=>$record_id,
            'bank_id'=>$bank_id,
            'bank_branch_id'=>$branch_id,
            'username'=>$username,
            'fname'=>$fname,
            'lname'=>$lname,
            'mname'=>$mname,
            'user_type'=>'bank_user',
            'user_level'=>$user_level,
            'active'=>$active,
            'modified_by'=>$bank_user_id
        ));

        $pass = '';
        if ($type == 'add') {
            $data['BankUser']['created_by'] = $bank_user_id;
            $pass = $this->randomPassString(8);
            $data['BankUser']['password'] = md5($pass);
        }
        else{
            $bk_user = $this->BankUser->getUserById($record_id);
            if ($bk_user['BankUser']['active'] == 'Disabled' && $_POST['active'] == 'Enabled') {
                $data['BankUser']['bg_color'] = '';
                $modObj = ClassRegistry::init('BankFailedLogin');
                $re = $modObj->deleteAll(array('BankFailedLogin.username' => $_POST['username']), false);
            }
        }

        if ($this->BankUser->save($data['BankUser'])) {
            $status = true;
            if ($type == 'add') {
                $msg = 'User Data Saved!  The default password is ' . $pass;
                $return_arr = array('id' => $this->BankUser->id);
            }
            else{
                $msg = 'User Data Updated';
                $return_arr = array();
            }
        }
        else {
            $status = false;
            $return_arr = array();
            $msg = 'User Data Processing Failed';
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }


    private function _validateUsername($username = null)
    {
        $data = $this->BankUser->find('first', array(
            'conditions' => array('BankUser.username' => $username),
            'recursive' => -1
        ));

        if ($data) {
            return true;
        } else {
            return false;
        }
    }


    private function randomPassString($length)
    {
        return $this->randomString($length);
    }


    public function delete_users()
    {
        $this->autoLayout = false;

        $data = $this->request->data;
        $user_ids = $data['user_ids'];
        $bank_user_id = $data['bank_user_id'];
        $status = false;
        $return_arr = array();
        $msg = '';

        $result = $this->BankUser->updateAll(
            array('BankUser.deleted' => "'y'",'BankUser.modified_by' => $bank_user_id),
            array('BankUser.id' => $user_ids)
        );
        if ($result) {
            $status = true;
            $return_arr = array();
            $msg = 'User Profile(s) Deleted';
        }
        else {
            $status = false;
            $return_arr = array();
            $msg = 'Cannot Delete User Profile(s)';
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }


    public function reset_password()
    {
        $this->autoLayout = false;

        $data = $this->request->data;
        $user_id = $data['user_id'];
        $password = $data['password'];
        $bank_user_id = $data['bank_user_id'];
        $status = false;
        $return_arr = array();
        $msg = '';
        $new_pass = md5(trim($password));
        $result = $this->BankUser->save(array(
                'id'=>$user_id,
                'password' => $new_pass,
                'modified_by' => $bank_user_id
             )
        );

        if ($result) {
            $status = true;
            $return_arr = array();
            $msg = 'User Password Reset';
        }
        else {
            $status = false;
            $return_arr = array();
            $msg = 'Cannot Rest User Password';
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }



    public function modify_branch()
    {
        $this->autoLayout = false;

        $data = $this->request->data;
        $type = $data['type'];
        $bank_id = $data['bank_id'];
        $branch_id = $data['branch_id'];
        $branch_name = $data['branch_name'];
        $branch_code = $data['branch_code'];
        $branch_name_full = $data['branch_full_name'];
        $address = $data['address'];
        $phone1 = $data['phone1'];
        $phone2 = $data['phone2'];
        $bank_user_id = $data['bank_user_id'];

        $status = true;
        $return_arr = array();
        $msg = '';

        $record_id = $branch_id;

        $data = array('BankBranch' => array(
            'id'=>$record_id,
            'bank_id'=>$bank_id,
            'branch_name'=>$branch_name,
            'branch_code'=>$branch_code,
            'branch_name_full'=>$branch_name_full,
            'address'=>$address,
            'phone1'=>$phone1,
            'phone2'=>$phone2,
            'modified_by'=>$bank_user_id
        ));

        $pass = '';
        if ($type == 'add') {
            $data['BankBranch']['created_by'] = $bank_user_id;
        }

        if ($this->BankBranch->save($data['BankBranch'])) {
            $status = true;
            if ($type == 'add') {
                $msg = 'Branch Data Saved!';
                $return_arr = array('id' => $this->BankBranch->id);
            }
            else{
                $msg = 'Branch Data Updated';
                $return_arr = array();
            }
        }
        else {
            $status = false;
            $return_arr = array();
            $msg = 'Branch Data Processing Failed';
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }


    public function delete_branches()
    {
        $this->autoLayout = false;

        $data = $this->request->data;
        $branch_ids = $data['branch_ids'];
        $bank_user_id = $data['bank_user_id'];
        $status = false;
        $return_arr = array();
        $msg = '';

        $result = $this->BankBranch->updateAll(
            array('BankBranch.deleted' => "'y'",'BankBranch.modified_by' => $bank_user_id),
            array('BankBranch.id' => $branch_ids)
        );
        if ($result) {
            $status = true;
            $return_arr = array();
            $msg = 'Branch(es) Deleted';
        }
        else {
            $status = false;
            $return_arr = array();
            $msg = 'Cannot Delete Branch(es)';
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }



    public function get_fee_payments()
    {
        $this->autoLayout = false;

        $data = $this->request->data;
        $type = $data['type'];
        $start = $data['start'];
        $end = isset($data['end'])?$data['end']:null;
        $bank_id = $data['bank_id'];
        $branch_code = isset($data['branch_code'])?$data['branch_code']:null;
        $status = false;
        $return_arr = array();
        $msg = '';

        $conditions = array();
        $limit = 2000; //Dowload and process 2000 records per download
        if ($type == 'new') {
            $conditions = array('Transaction.bank_id' => $bank_id, 'Transaction.id > ' => $start, 'Transaction.trans_type' => array('fee_payment','service_charge'));
        } elseif ($type == 'history') {
            $conditions = array('Transaction.bank_id' => $bank_id, 'Transaction.id >= ' => $start, 'Transaction.id <= ' => $end, 'Transaction.trans_type' => array('fee_payment','service_charge'));
        }
        $find_params = array(
            'fields' => array('Transaction.id','Transaction.trans_type','Transaction.trans_ref_no','Transaction.source_funds', 'Transaction.student_user_id', 'Transaction.created'),
            'conditions' => $conditions,
            'contain' => array(
                'TransactionItem' => array(
                    'fields' => array('TransactionItem.id', 'TransactionItem.credit_amt', 'TransactionItem.trans_currency', 'TransactionItem.fee_id','TransactionItem.actual_trans_type'),
                    'Fee' => array(
                        'fields' => array('Fee.id', 'Fee.fee_type_id')
                    )
                ),
                'StudentUser' => array('fields' => array('StudentUser.id', 'StudentUser.fname', 'StudentUser.mname', 'StudentUser.lname', 'StudentUser.index_number'))
            ),
            'order' => array('Transaction.id' => 'ASC'),
            'recursive' => 2
        );
        if ($type == 'new') {
            $find_params['limit'] = $limit;
        }

        $trans_data1 = $this->Transaction->find('all', $find_params);
		

        $trans_data = array();
        foreach ($trans_data1 as $key => $value) {
            $count = count($value['TransactionItem']);
            if ($count == 1) {
                if ($value['TransactionItem'][0]['actual_trans_type'] == 'fee_payment' && empty($value['TransactionItem'][0]['Fee'])) {
                    //debug($value);
                } else {
                    $trans_data[$key] = $value;
                }
            } else {
                foreach ($value['TransactionItem'] as $key2 => $item) {
                    if ($item['actual_trans_type'] == 'fee_payment' && empty($item['Fee'])) {

                    } else {
                        $trans_data[$key]['Transaction'] = $value['Transaction'];
                        $trans_data[$key]['StudentUser'] = $value['StudentUser'];
                        $trans_data[$key]['TransactionItem'][$key2] = $item;
                    }
                }
            }
        }

        //VERY IMPORTANT QUERY HAS TO FILTER ON THE CURRENT BANK OF THE USER BRANCH CODE
        //Consider tying using branch from current login user and using that to filter on data rather than tying branch id to FeeType, what if in the future many branch what to use the sam Feetypes ?
        $user_branch_code = $branch_code;//Branch code of the user who downloaded the file

        foreach ($trans_data as $key => $value) {
            foreach ($value['TransactionItem'] as $key2 => $item) {

                if($item['actual_trans_type'] == 'service_charge'){
                    $feetype_id = '23'; //Reserved id for service charge
                }
                elseif($item['actual_trans_type'] == 'service_charge_upsa'){
                    $feetype_id = '25'; //Reserved id for service charge upsa
                }
                else{
                    $feetype_id = $item['Fee']['fee_type_id'];
                }

                $feetype_data = $this->FeeType->find('first', array(
                    'fields' => array('FeeType.id', 'FeeType.fee_category', 'FeeType.description', 'FeeType.account_no', 'FeeType.bank_branch_id'),
                    'conditions' => array('FeeType.id' => $feetype_id),
                    'contain' => array('BankBranch' => array('fields' => array('BankBranch.id', 'BankBranch.branch_name', 'BankBranch.branch_code'))),
                    'recursive' => 1
                ));
                //if($user_branch_code == $feetype_data['BankBranch']['branch_code']){
                //$trans_data[$key] = $value;
                //$trans_data[$key]['Transaction']['branch_code']=$feetype_data['BankBranch']['branch_code'];
                $trans_data[$key]['Transaction']['branch_code'] = $user_branch_code;
                $trans_data[$key]['TransactionItem'][$key2]['FeeType'] = $feetype_data['FeeType'];
                $trans_data[$key]['TransactionItem'][$key2]['BankBranch'] = $feetype_data['BankBranch'];
                // }
            }
        }


        if ($trans_data) {
            $status = true;
            $return_arr = $trans_data;
            $msg = 'Fee Payments Transactions Found';
        }
        else {
            $status = false;
            $return_arr = array();
            $msg = 'Fee Payments Transactions Not Found';
        }

        $result = array(
            'response_code'=>1,
            'message'=>$msg,
            'data'=>$return_arr
        );
        if ($status) {
            $result = array(
                'response_code'=>0,
                'message'=>$msg,
                'data'=>$return_arr
            );
        }

        return $this->_response($result);
    }

    /************************** END BANK ADMIN SECTION *******************/

}